Writing correct and robust JavaScript

By Bad Sector / Nasty Bugs

Before I commence this article, I would like to state that I could have saved it for the first issue of the diskmag of my own group (Nasty Bugs), which is going to be called Obscurum, instead of publishing it in Hugi. (And since not a single paragraph has been sent to me by any external contributor yet many months after the first announcement, I ought to have done that.) However, since the development of "Obscurma", the future engine of the Obscurum magazine, is making slow headways (after all, it's not my first priority; that's why I don't invest all my time in it), I don't think that it will be ready before the release of Hugi #27 - probably it won't even be ready until the release of Hugi #28. So I've submitted my article to the Hugi Magazine.

Ok, now the actual article is going to start...

In the previous issue of Hugi (#26) there was an article from TAD about JavaScript and DOM. The article you are now reading is supposed to be a sequel to TAD's article. My intentionis to give you some tips and explain a couple of methods regarding the matter how to write correct and robust JavaScript code. My understanding of "correct" code is code that uses the W3C's DOM, and my understanding of "robust" code is code that will work on the majority of common browsers that sticks to the standards (in some way or another). Here we go...

Say that you are using JavaScript

A real lot of web developers forget to inform the web browser about the scripting language they use by writing <script> into their code without providing any additional information. Even though this works okay with IE and Mozilla (Netscape 6, 7+), it may fail with other browsers and it is against the standards. (Unfortunatelly, standards are agreed on with the intention that developers stick to them.) The correct usage of the <script> tag is the following:

<script type="text/javascript">alert("aloha!");</script>

Note that the following:

<script language="javascript">...

is obsolete by the latest HTML definitions and should no longer be used (however, I'm seeing it in almost every <script> tag... that's the fault of Frontpage...).

Forget the "evil IE way"

One bad thing many web developers do is to use the "id" attribute of an element in order to access it directly. This is the well-known evil IE way (as described in one of Mozilla's source code files :-). Need an example?

HTML Code:

<div id="boo">blaah</div>JavaScript:boo.style.backgroundColor = "red";

This is bad and wrong! It will work with IE, but not with Mozilla/Netscape (and others) and W3C's DOM doesn't give you permission to do so. The correct way is to use the getElementById function. The corrected code looks as follows:

document.getElementById("boo").style.backgroundColor = "red";

However, if you access this element too often, you may want to assign it to a variable. Example:

var boo = document.getElementById("boo");

(Hereby you have just forced the browser to do what IE usually does automatically, without asking the user.)

Ok, that would be perfect if IE4 didn't complain about getElementById. However, it does... and does so because it doesn't support getElementById (IE5 and newer do support it). Fortunately, if you say <object>.<field> to JavaScript and the "object" doesn't have the given "field", it will return "undefined", which is something similar to NULL in C. So in order to make your JavaScript code robust you could write:

var booVar;
if (document.getElementById)  booVar = document.getElementById("boo");
else  booVar = boo;

(Don't think about renaming "booVar" to "boo" and removing the "else" branch just because boo will be already defined; with "var boo" you'll undefine it.)

If it doesn't work with IE, don't use it

Okay, I'm a fan of Mozilla since IE (even IE6) doesn't care about standards (and just mind the fact that Microsoft is a member of the W3C...). But most people use IE, so it is not a good idea to use code that doesn't work with IE (even if matches the W3C standards!) Want an example? Here it is:

object.onXXXX = myEventHandler;function myEventHandler(ev){ // code}

The standards are saying that the browser must pass information about the event in "ev". However, IE doesn't do that; instead, it passes the information in a (global?) variable called "event" (something that Mozilla and other W3C followers don't do). The solution here is simple:

function myEventHandler(ev){ if (!ev) ev = event; // code}

However, note that this may not work well with all browsers (for example, I haven't tested it with IE4 - but it definitely works with both IE5 and newer and of course Mozilla), so use this syntax only if you are really in need for information about the event. In other cases, use the old, good syntax:

object.onXXXX = "myEventHandler();"

(Okay, I haven't tested that with IE4 either, but I've seen it in HTML sources for years, so I believe that IE4 supports this way... However, in case it doesn't, just use the onXXXX attribute of the element, if that's possible.)

Read the standards - They're FREE!

W3C has defined standards for almost everything that you may find on the Web and allows you to read them for free. So visit their main site, pick a section from the left panel and download an offline version of the specs (the HTML zipped versions are the best ones in my opinion, except if you want to print them - in this case get the PDF version, if there is one). Personally I'm trying to create pages that follow the standards (except if it is not my intention). It's not that hard and I recommend that you try it, too.

W3C also has a service that "validates" your HTML page to see if it is correct (which it is if it doesn't produce any errors and warnings and proposes you to put a "button" on your page that says that you took care to follow the standards and make an interoperatable web page - in theory). The HTML validator page also contains a link to a CSS validator.

Inspecting DOM

In the bonus pack attached to this Hugi issue, you'll find a file named inspect.htm. This is a simple DOM inspector written in JavaScript and it is assumed to work with any web browser compatible with the standards (e.g. Mozilla). The inspector will certainly work under Mozilla 1.3a and other Gecko-based web browsers as well as Microsoft Internet Explorer 6. (MSIE 5 and earlier are not supported. I haven't tested 5.5, but the program may work with it, since MSIE 5.5 is very similar to version 6). It also may work with Opera 7; however, I'm not that sure about Opera 6.

The usage of this inspector is very simple: At the beginning it displays the nodes of the document object (that's right: DOM is actually a tree). Click on one of the nodes and it will expand to its value and its child nodes.

Conclusion

I hope that this small article has helped you create better web pages which can be viewed by more people. Keep in mind that almost everything (95 %) that is IE-specific can be done sticking to the standards, too. Try to inform others about this article, teach them how to create correct pages and help making those "this page works only under IE" pages disappear from the Internet.

Links

http://www.w3c.org/ - W3C, the mother of the standards. A must-visit for every web developer.

http://www.mozilla.org/ - The Mozilla Project - a standards-compatible multiplatform Web Browser (which rulez!). On their web developing documentaton page, you'll also find links for JavaScript 1.5 (the most advanced JavaScript ever - which is supported by Mozilla).

http://www.netscape.com/ - Somewhere on their developers site you'll find information about converting IE and Netscape-specific code to W3C code (and other useful things).

http://www.mozdev.org/ - The power of JavaScript to its full extent: Plugins and Extensions for Mozilla written entirely in JavaScript and XUL (XUL is Mozilla's XML User interface Language).

http://bricks.bsector.cjb.net/ - And for the last link, take a look what I did using plain JavaScript :-)

Bad Sector / Nasty Bugs